// pages/search/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchValue: '',
    searchHistory: [],
    navBarHeight: 0,
    
    // 搜索类型：activity 或 goods
    searchType: 'activity',
    
    // 搜索结果
    searchResults: [],
    isSearching: false,
    hasSearched: false,
    
    // 分页相关
    currentPage: 0,
    pageSize: 10,
    hasMoreData: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.calculateNavBarHeight()
    this.loadSearchHistory()
  },

  /**
   * 计算导航栏高度
   */
  calculateNavBarHeight() {
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    // 导航栏高度 = 状态栏高度 + 44px(导航栏内容高度)
    const navBarHeight = statusBarHeight + 44
    this.setData({ navBarHeight })
  },

  /**
   * 加载搜索历史
   */
  loadSearchHistory() {
    const history = wx.getStorageSync('searchHistory') || []
    this.setData({ searchHistory: history })
  },

  /**
   * 保存搜索历史
   */
  saveSearchHistory(keyword) {
    if (!keyword.trim()) return
    
    let history = this.data.searchHistory.filter(item => item !== keyword)
    history.unshift(keyword)
    history = history.slice(0, 10) // 最多保存10条
    
    this.setData({ searchHistory: history })
    wx.setStorageSync('searchHistory', history)
  },

  /**
   * 返回按钮点击处理
   */
  handleBack() {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 搜索类型切换
   */
  onSearchTypeChange(e) {
    const type = e.currentTarget.dataset.type
    this.setData({
      searchType: type,
      searchResults: [],
      hasSearched: false,
      currentPage: 0,
      hasMoreData: true
    })
  },

  /**
   * 搜索处理
   */
  onSearch(e) {
    const keyword = e.detail.value.trim()
    if (!keyword) return
    
    this.saveSearchHistory(keyword)
    this.performSearch(keyword)
  },

  /**
   * 执行搜索
   */
  async performSearch(keyword, loadMore = false) {
    if (this.data.isSearching) return
    
    try {
      this.setData({ isSearching: true })
      
      if (!loadMore) {
        this.setData({
          searchResults: [],
          currentPage: 0,
          hasMoreData: true,
          hasSearched: true
        })
      }

      const result = await wx.cloud.callFunction({
        name: 'searchContent',
        data: {
          keyword: keyword,
          type: this.data.searchType,
          limit: this.data.pageSize,
          skip: this.data.currentPage * this.data.pageSize
        }
      })

      console.log('搜索结果：', result)

      if (result.result && result.result.success) {
        const newResults = result.result.data || []
        
        let updatedResults = []
        if (loadMore) {
          updatedResults = [...this.data.searchResults, ...newResults]
        } else {
          updatedResults = newResults
        }

        this.setData({
          searchResults: updatedResults,
          currentPage: this.data.currentPage + 1,
          hasMoreData: newResults.length === this.data.pageSize,
          searchValue: ''
        })

        if (updatedResults.length === 0 && !loadMore) {
          wx.showToast({
            title: '未找到相关内容',
            icon: 'none',
            duration: 2000
          })
        }
      } else {
        wx.showToast({
          title: '搜索失败，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('搜索出错：', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.setData({ isSearching: false })
    }
  },

  /**
   * 点击历史记录搜索
   */
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.performSearch(keyword)
  },

  /**
   * 活动卡片点击事件
   */
  onActivityCardTap(e) {
    const { item } = e.detail
    const activityId = item._id || item.id
    console.log('点击活动卡片，ID:', activityId)
    
    if (!activityId) {
      wx.showToast({
        title: '活动信息错误',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/activity_detail/index?id=${activityId}`,
      success: () => {
        console.log('成功跳转到活动详情页')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 商品点击事件
   */
  onProductTap(e) {
    const productId = e.currentTarget.dataset.id
    console.log('点击商品:', productId)
    wx.navigateTo({
      url: `/pages/goods_detail/index?id=${productId}`
    })
  },

  /**
   * 清空搜索历史
   */
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ searchHistory: [] })
          wx.removeStorageSync('searchHistory')
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasSearched && this.data.hasMoreData && this.data.searchHistory.length > 0) {
      const lastKeyword = this.data.searchHistory[0]
      this.performSearch(lastKeyword, true)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})